package org.zh.svs.pro.remote;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.Part;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * webflux   上传  例子
 */

@RestController
public class ProductRemote2Impl {


    @RequestMapping(method = RequestMethod.POST, path = "/testObjectArray", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Mono<Map<String, String>> testObjectArray(ServerWebExchange exchange) {
        return exchange.getMultipartData().map(mvm -> {
            Map<String, String> map = new ConcurrentHashMap<>();
            mvm.forEach((d, v) -> {
                for (Part part : v) {
                    HttpHeaders headers = part.headers();
                    String name = headers.getContentDisposition().getName();
                    String filename = headers.getContentDisposition().getFilename();
                    if (filename == null) {
                        part.content().next().subscribe(dataBuffer -> {
                            String value = dataBuffer.toString(StandardCharsets.UTF_8);
                            map.put(name, value);
                        });
                    } else {
                        part.content().next().subscribe(dataBuffer -> {
                            try {
                                File file = new File("D:\\" + filename);
                                if (!file.exists()) {
                                    file.createNewFile();
                                }
                                FileOutputStream fileOutputStream = new FileOutputStream(file);
                                fileOutputStream.write(dataBuffer.asInputStream().readAllBytes());
                                fileOutputStream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                            map.put(name, filename);
                        });
                    }
                }
            });
            return map;
        });
    }
}
